package com.gitee.vueantd.common.utils.download;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

@Log4j2
public class HttpLocalFilesReader extends AbstractHttpFilesReader {
  @Override
  public void setFileList(List<HttpFileInfo> httpFileInfoList) throws Exception {
    for (HttpFileInfo httpFileInfo : httpFileInfoList) {
      File file = FileUtils.getFile(httpFileInfo.getFileName());
      this.httpFileInfoList.add(new HttpFileInfo(file.length(), httpFileInfo.getFileName()));
    }
  }

  @Override
  public long read(HttpFileInfo httpFileInfo, long pos, long len, OutputStream outputStream, BandWidthLimiter limiter) throws Exception {
    long bufferReaded = 0;
    try (InputStream inputStream = new FileInputStream(FileUtils.getFile(httpFileInfo.getFileName()))) {
      inputStream.skip(pos);
      log.debug("enter pos = {}, len = {}", pos, len);
      bufferReaded = readData(inputStream, pos, len, outputStream, limiter);
      log.debug("leave pos = {}, len = {}", pos, len);
    } catch (Exception e) {
      log.debug("exception pos = {}, len = {}, e = {}", pos, len, e);
      throw e;
    }
    return bufferReaded;
  }
}
